﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using QuickWeb.Resources;
using System.Windows.Media;
using System.Windows.Input;
using Microsoft.Phone.Tasks;
using System.Windows.Media.Imaging;
using System.ServiceModel.Syndication;
using System.Windows.Data;
using System.Collections.ObjectModel;
using System.ComponentModel;

namespace QuickWeb
{

    

    public partial class MainPage : PhoneApplicationPage
    {

        private string searchString;

        private bool resultPresentQVar;
        public bool resultPresentQ
        {
            get { return resultPresentQVar; }
            set { resultPresentQVar = value; }
        }

        private FeedsStoredContext storedFeedsDB;
        private ObservableCollection<FeedStored> _FeedStoredItems;
        public ObservableCollection<FeedStored> FeedStoredItems
        {
            get
            {
                return _FeedStoredItems;
            }
            set
            {
                if (_FeedStoredItems != value)
                {
                    _FeedStoredItems = value;
                    NotifyPropertyChanged("FeedStoredItems");
                }
            }
        }

        private ClipsStoredContext storedClipsDB;
        private ObservableCollection<ClipStored> _ClipsStoredItems;
        public ObservableCollection<ClipStored> ClipsStoredItems
        {
            get
            {
                return _ClipsStoredItems;
            }
            set
            {
                if (_ClipsStoredItems != value)
                {
                    _ClipsStoredItems = value;
                    NotifyPropertyChanged("ClipsStoredItems");
                }
            }
        }


        ProgressIndicator progressBar;
        ApplicationBarIconButton appBarButton;
        ApplicationBarIconButton addFeedButton;
        AppSettings settings;
        // Constructor
        public MainPage()
        {
            
            InitializeComponent();
            

            storedFeedsDB = new FeedsStoredContext(FeedsStoredContext.DBConnectionString);
            storedClipsDB = new ClipsStoredContext(ClipsStoredContext.DBConnectionString);

            this.DataContext = this;



            resultPresentQ = false;

            progressBar = new ProgressIndicator();
            //progressBar.IsVisible = true;
            //progressBar.IsIndeterminate = false;
            //progressBar.Text = "";
            SystemTray.SetProgressIndicator(this, progressBar);
            //Visibility v = (Visibility)Resources["PhoneLightThemeVisibility"];
            //string iconString = "";
            //iconString = "/Assets/overflowdots_dark.png";
            //Image im = new Image();
            //BitmapImage myBitmapImage = new BitmapImage(new Uri(iconString, UriKind.Relative));
            //myBitmapImage.DecodePixelHeight = 47;
            //myBitmapImage.DecodePixelWidth = 117;

            //im.Source = myBitmapImage;
            //settingsButton.Content = im;
            BuildLocalizedApplicationBar();
            

            //Leer la configuracion actual
            settings = new AppSettings();
            pivot.SelectedIndex = settings.StartPivot;
            switch(settings.SearchEngine){
                case 1: {
                    searchString = AppResources.SearchGoogle;
                    break;
                }
                case 2:
                {
                    searchString = AppResources.SearchDuckDuckGo;
                    break;
                }
                default: {
                    searchString = AppResources.SearchBing;
                    break;
                }
            }

            //Elementos de prueba
            feedsSourceList.ItemsSource = null;
            clipsList.ItemsSource = null;
            searchBox.Text = searchString;
            


        }

       

        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            settings = new AppSettings();
            switch (settings.SearchEngine)
            {
                case 1:
                    {
                        searchString = AppResources.SearchGoogle;
                        break;
                    }
                case 2:
                    {
                        searchString = AppResources.SearchDuckDuckGo;
                        break;
                    }
                default:
                    {
                        searchString = AppResources.SearchBing;
                        break;
                    }
            }
            
            var itemsInDB = from FeedStored item in storedFeedsDB.items
                            select item;
            FeedStoredItems = new ObservableCollection<FeedStored>(itemsInDB);
            if (FeedStoredItems.Count > 0)
            {
                feedsSourceList.ItemsSource = FeedStoredItems;
                feedsSourceList.Visibility = Visibility.Visible;
                noItemsTipText.Visibility = Visibility.Collapsed;
            }
            else {
                feedsSourceList.Visibility = Visibility.Collapsed;
                noItemsTipText.Visibility = Visibility.Visible;
                noItemsTipText.Text = AppResources.noSourcesText;
            }

            
            
            
            var clipsInDB = from ClipStored item in storedClipsDB.items
                            select item;
            ClipsStoredItems = new ObservableCollection<ClipStored>(clipsInDB);
            if (ClipsStoredItems.Count > 0)
            {
                clipsList.ItemsSource = ClipsStoredItems;
                clipsList.Visibility = Visibility.Visible;
                noClipsTipText.Visibility = Visibility.Collapsed;
            }
            else
            {
                clipsList.Visibility = Visibility.Collapsed;
                noClipsTipText.Visibility = Visibility.Visible;
                noClipsTipText.Text = AppResources.noClipsText;
            }


            
            base.OnNavigatedTo(e);
            searchBox.Text = searchString;
        }

        protected override void OnNavigatedFrom(System.Windows.Navigation.NavigationEventArgs e)
        {
            base.OnNavigatedFrom(e);
            //Guardar los resultados a la base de datos
            storedFeedsDB.SubmitChanges();
        }

        private void Pivot_Loaded(object sender, RoutedEventArgs e)
        {
            
        }

        private void searchBox_GotFocus(object sender, RoutedEventArgs e)
        {
            if (searchBox.Text == searchString)
            {
                searchBox.Text = "";
                SolidColorBrush Brush1 = new SolidColorBrush();
                Brush1.Color = Colors.Black;
                searchBox.Foreground = Brush1;                
            }
            else {
                searchBox.SelectAll();
            }
        }

        private void searchBox_LostFocus(object sender, RoutedEventArgs e)
        {
            if (searchBox.Text == String.Empty)
            {
                searchBox.Text = searchString;
                SolidColorBrush Brush2 = new SolidColorBrush();
                Brush2.Color = Colors.Gray;
                searchBox.Foreground = Brush2;
            }
        }

        private void searchBox_KeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
            {
                //browser.Visibility = Visibility.Visible;
                //progressBar.IsIndeterminate = true;
                //resultPresentQ = false;
                //browser.Source = new Uri("https://duckduckgo.com/?q="+searchBox.Text, UriKind.Absolute);
                //browser.Source = new Uri("https://www.google.com/search?q=" + searchBox.Text, UriKind.Absolute);
                //browser.Focus();
                //browserGrid.UpdateLayout();
                if (searchBox.Text.Length > 0)
                {
                    switch (settings.SearchEngine)
                    {
                        case 1: {
                            WebBrowserTask webBrowserTask = new WebBrowserTask();
                            webBrowserTask.Uri = new Uri("https://www.google.com/search?q=" + searchBox.Text, UriKind.Absolute);
                            webBrowserTask.Show();
                            break;
                        }
                        case 2:
                        {
                            WebBrowserTask webBrowserTask = new WebBrowserTask();
                            webBrowserTask.Uri = new Uri("https://duckduckgo.com/?q=" + searchBox.Text, UriKind.Absolute);
                            webBrowserTask.Show();
                            break;
                        }
                        default:{
                            SearchTask searchTask = new SearchTask();
                            searchTask.SearchQuery = searchBox.Text;
                            searchTask.Show();
                            break;
                        }
                    }

                   
                }
                
            }
        }

       
        private void settingsTriggered(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/SettingsPage.xaml", UriKind.Relative));
        }

        private void addFeed(object sender, EventArgs e)
        {
            NavigationService.Navigate(new Uri("/AddRSSFeedPage.xaml", UriKind.Relative));
        }

        // Build a localized ApplicationBar
        private void BuildLocalizedApplicationBar()
        {
            // Set the page's ApplicationBar to a new instance of ApplicationBar.
            ApplicationBar = new ApplicationBar();

            // Create a new button and set the text value to the localized string from AppResources.
            //Visibility v = (Visibility)Resources["PhoneLightThemeVisibility"];
            
            string settingsIconString ="/Assets/settings_dark.png";
            appBarButton =
                new ApplicationBarIconButton(new
                Uri(settingsIconString, UriKind.Relative));
            appBarButton.Text = AppResources.settings;
            ApplicationBar.Buttons.Add(appBarButton);
            appBarButton.Click += new EventHandler(settingsTriggered);


            string addFeedIconString = "/Assets/add_dark.png";
            addFeedButton =
                new ApplicationBarIconButton(new
                Uri(addFeedIconString, UriKind.Relative));
            addFeedButton.Text = AppResources.addFeed;
            ApplicationBar.Buttons.Add(addFeedButton);
            addFeedButton.Click += new EventHandler(addFeed);
            if (pivot.SelectedIndex == 0)
            {
                ApplicationBar.Buttons.Remove(addFeedButton);
            }
            else
            {
                ApplicationBar.Buttons.Add(addFeedButton);
            }

            ApplicationBar.Mode = ApplicationBarMode.Minimized;
            // Create a new menu item with the localized string from AppResources.
            //ApplicationBarMenuItem appBarMenuItem =
            //    new ApplicationBarMenuItem(AppResources.AppBarMenuItemText);
            //ApplicationBar.MenuItems.Add(appBarMenuItem);
        }

        private void Pivot_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if ((pivot.SelectedIndex == 0) | (pivot.SelectedIndex == 2) )
            {
                ApplicationBar.Buttons.Remove(addFeedButton);
            }
            else
            {
                ApplicationBar.Buttons.Add(addFeedButton);
            }
        }

        #region INotifyPropertyChanged Members
        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion

        private void RemoveFeed(object sender, RoutedEventArgs e)
        {
            var it = sender as MenuItem;
            if(it!=null){
                FeedStored entry = it.DataContext as FeedStored;
                FeedStoredItems.Remove(entry);
                storedFeedsDB.items.DeleteOnSubmit(entry);
                storedFeedsDB.SubmitChanges();

                this.Focus();

                if (FeedStoredItems.Count == 0)                
                {
                    feedsSourceList.Visibility = Visibility.Collapsed;
                    noItemsTipText.Visibility = Visibility.Visible;
                    noItemsTipText.Text = AppResources.noSourcesText;
                }

                
            }
            
        }

        

        

        private void feedsSourceList_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (FrameworkElement)e.OriginalSource;
            FeedStored feed = ((FeedStored)item.DataContext);
            int feedSourceID = feed.FeedSourceID;
            NavigationService.Navigate(new Uri("/RSSNews.xaml?msg=" + feedSourceID, UriKind.Relative));
        }

        private void clipsStoredList_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {
            var item = (FrameworkElement)e.OriginalSource;
            ClipStored clip = ((ClipStored)item.DataContext);
            WebBrowserTask webBrowserTask = new WebBrowserTask();
            webBrowserTask.Uri = new Uri(clip.Link);
            webBrowserTask.Show();
        }

        private void RemoveClip(object sender, RoutedEventArgs e)
        {
            var it = sender as MenuItem;
            if (it != null)
            {
                ClipStored entry = it.DataContext as ClipStored;
                ClipsStoredItems.Remove(entry);
                storedClipsDB.items.DeleteOnSubmit(entry);
                storedClipsDB.SubmitChanges();
                this.Focus();
                if (ClipsStoredItems.Count == 0)               
                {
                    clipsList.Visibility = Visibility.Collapsed;
                    noClipsTipText.Visibility = Visibility.Visible;
                    noClipsTipText.Text = AppResources.noClipsText;
                }



            }

        }

    }
}